<template>
  <div class="app-container">
    <!-- <div class="search-container">
      <el-form ref="form" :model="queryParams" :inline="true">
        <el-form-item>
          <el-button type="primary" @click="handleQuery" icon="el-icon-search">搜索</el-button>
          <el-button type="warning" @click="openSearchDialog()"><i class="el-icon-mouse"></i> 高级查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

    </div> -->

    <el-card shadow="never">
      <template #header>
        <el-button type="success" @click="openDialog()"
          ><i class="el-icon-circle-plus"></i> 新增</el-button>
        <!-- <el-button
            type="warning"
            link
            @click="openUploadSampleDialog()"
          ><i class="el-icon-edit"></i> 导入样本</el-button> -->
        <el-button type="warning" @click="openSearchDialog()"><i class="el-icon-mouse"></i> 高级查询</el-button>
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="handleDelete()"
          ><i class="el-icon-delete"></i> 删除</el-button>
      </template>

      <el-table
        v-loading="loading"
        :data="dataList"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="Fastq1">
                <span>{{ props.row.fastq1 }}</span>
              </el-form-item>
              <el-form-item label="Fastq2">
                <span>{{ props.row.fastq2 }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="序号" width="55" prop="dataIndex"/>
        <el-table-column label="样本名称" prop="name"/>
        <el-table-column label="样本分组" prop="group"/>
        <el-table-column label="物种" prop="speciesText"/>
        <el-table-column label="实验策略" prop="strategy"/>
        <el-table-column label="测序方式" prop="layoutText"/>
        <el-table-column fixed="right" label="操作"  min-width="320" width="320">
          <template #default="scope">
            <el-button
              type="warning"
              size="small"
              link
              @click="openDialog(scope.row)"
            ><i class="el-icon-edit"></i> 编辑</el-button>
            
            <el-button
              type="primary"
              size="small"
              link
              @click="sendKafka(scope.row)"
            ><i class="el-icon-s-promotion"></i> 发送至Kafka</el-button>
            <el-button
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row)"
            ><i class="el-icon-delete"></i> 删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 文献表单弹窗 -->
    <el-dialog
      :visible.sync="dialog.visible"
      :title="dialog.title"
      width="900px"
      :before-close="closeDialog"
    >
      <el-form
        ref="seqSampleFormRef"
        :model="formData"
        :rules="seqSampleRules"
        label-width="150px"
      >
        <el-form-item label="样本名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入样本名称" />
        </el-form-item>
        <el-form-item label="样本分组" prop="group">
          <el-input v-model="formData.group" placeholder="请输入样本分组" />
        </el-form-item>
        <el-form-item label="物种" prop="species">
          <el-select v-model="formData.species" placeholder="请选择物种">
            <el-option v-for="item in dictSpeciesList" :key="item.id" :label="item.name" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="实验策略" prop="strategy">
          <el-select v-model="formData.strategy" placeholder="请选择实验策略">
            <el-option v-for="item in dictStrategyList" :key="item.id" :label="item.name" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="测序方式" prop="layout">
          <el-select v-model="formData.layout" placeholder="请选择测序方式">
            <el-option label="单端测序" value="SINGLE"></el-option>
            <el-option label="双端测序" value="PAIRED"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属项目" prop="seqProjectId">
          <el-select v-model="formData.seqProjectId" placeholder="请选择所属项目">
            <el-option v-for="field in projectList" :key="field.id" :label="field.name" :value="field.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="fastq1" prop="fastq1">
          <el-input v-model="formData.fastq1" placeholder="请输入fastq1" />
        </el-form-item>
        <el-form-item label="fastq2" prop="fastq2" v-show="formData.layout == 'PAIRED'">
          <el-input v-model="formData.fastq2" placeholder="请输入fastq2" />
        </el-form-item>
        <el-form-item label="样本备注/描述" prop="remark">
          <el-input v-model="formData.remark" type="textarea" :rows="4" placeholder="请输入样本备注/描述" />
        </el-form-item>
        <el-form-item label="运行结果" prop="resultContent">
          <el-input v-model="formData.resultContent" type="textarea" :rows="2" placeholder="请输入运行结果" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addOrUpdate">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      :visible.sync="searchDialog"
      title="高级查询"
      width="500px"
      :before-close="closeSearchDialog"
    >
      <el-form
        ref="searchFormRef"
        :model="formData"
        :rules="rules"
        label-width="0px"
      >
      <el-form-item v-for="(item, index) in searchFormData" :key="index" label-width="0">
          <el-col :span="7">
            <el-select v-model="searchFormData[index].name">
              <el-option v-for="field in fieldList" :key="field.value" :label="field.label" :value="field.value"></el-option>
            </el-select>
          </el-col>
          <el-col :span="1">&nbsp;</el-col>
          <el-col :span="4">
            <el-select v-model="searchFormData[index].searchType">
              <el-option v-for="cont in contList" :key="cont.value" :label="cont.label" :value="cont.value"></el-option>
            </el-select>
          </el-col>
          <el-col :span="1">&nbsp;</el-col>
          <el-col :span="7">
            <el-select v-model="searchFormData[index].searchVal" v-if="searchFormData[index].name === 'strategy'">
              <el-option label="Amplicon" value="Amplicon"></el-option>
              <el-option label="Metagenomics" value="Metagenomics"></el-option>
              <el-option label="WES" value="WES"></el-option>
            </el-select>
            <el-select v-model="searchFormData[index].searchVal" v-else-if="searchFormData[index].name === 'layout'">
              <el-option label="单端测序" value="SINGLE"></el-option>
              <el-option label="双端测序" value="PAIRED"></el-option>
            </el-select>
            <el-input v-model="searchFormData[index].searchVal" placeholder="请输入查询内容" v-else></el-input>
          </el-col>
          <el-col class="line" :span="4"><i class="el-icon-remove-outline" style="font-size: 22px; cursor: pointer; margin-left: 5px;" @click="delSearchFormData(index)"></i></el-col>
        </el-form-item>
        
      </el-form>
      <div style="margin-top: 10px;">
        <i class="el-icon-circle-plus-outline" style="font-size: 22px; cursor: pointer;" @click="addSearchFormData"></i>
        
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="search">查 询</el-button>
          <el-button @click="closeSearchDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      :visible.sync="uploadSampleDialog.visible"
      :title="uploadSampleDialog.title"
      width="800px"
      :before-close="closeUploadSampleDialog">
      <el-form
        ref="uploadSampleFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px">
        <el-form-item label="所属项目" prop="projectId">
          <el-select v-model="uploadSampleForm.projectId" placeholder="请输入所属项目">
            <el-option v-for="field in projectList" :key="field.id" :label="field.name" :value="field.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文件内容" prop="content">
          <el-input v-model="uploadSampleForm.content" type="textarea" :autosize="{ minRows: 10, maxRows: 50}" placeholder="请输入文件内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="uploadSample">上传样本</el-button>
          <el-button @click="closeUploadSampleDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>

import seqSampleApi from '@/api/sequence/seqSample'
import seqProjectApi from '@/api/sequence/project'

import dictApi from '@/api/system/dict'
import followDictApi from '@/api/system/followDict'
import { formatDate } from '@/utils/formatTime'
import qs from 'qs';
export default {
	name: 'seqDataIndex',
	data() {
		return {
			queryParams: {
        pageNum: 0,
        pageSize: 10,
        criteriaVos: [{
          name: 'sampleType',
          searchType: 'EQUAL',
          searchVal: 'SCIENTIFIC_RESEARCH'
        }],
      },
      total: 0,
      loading: false,
      dataList: [],
      ids: [],
      dialog: {},
      formData: {},
      rules: {},
      seqSampleRules: {
        name: [{ required: true, message: '请输入样本名称', trigger: 'blur' }],
        group: [{ required: true, message: '请输入样本分组', trigger: 'blur' }],
        species: [{ required: true, message: '请选择物种', trigger: 'change' }],
        strategy: [{ required: true, message: '请选择实验策略', trigger: 'change' }],
        layout: [{ required: true, message: '请选择测序方式', trigger: 'change' }],
        seqProjectId: [{ required: true, message: '请选择所属项目', trigger: 'change' }],
      },

      fieldList: [{label: '样本名称', value: 'name'}, {label: '测序方式', value: 'layout'}, {label: 'fastq1', value: 'fastq1'}, {label: 'fastq2', value: 'fastq2'}
        , {label: '实验策略', value: 'strategy'}, {label: 'group', value: 'group'}],
      contList: [{label: 'LIKE', value: 'LIKE'}, {label: '等于', value: 'EQUAL'}, {label: '大于', value: 'GT'}, {label: '大于等于', value: 'GTE'}
        , {label: '小于', value: 'LT'}, {label: '小于等于', value: 'LTE'}],
      searchDialog: false,
      searchFormData: [],
      typeMap: {'PUBLICATION': '测序样本', 'SCIENTIFIC_RESEARCH': '科研样本', 'REPORT': '报告样本'},

      uploadSampleDialog: {},
      uploadSampleForm: {},
      projectList: [],

      speciesMap: {
        human: '人类',
        hat: '小鼠',
        mouse: '大鼠',
      },
      dictStrategyList: [],
      dictSpeciesList: [],

		};
	},
  methods: {
    uploadSample () {
      seqSampleApi.uploadResearchSample(this.uploadSampleForm).then(res => {
        this.$message({message: '样本数据解析完成！', type: 'success'});
        this.handleQuery();
        this.$set(this.uploadSampleDialog, 'visible', false);
      })
    },
    closeUploadSampleDialog () {
      this.$set(this.uploadSampleDialog, 'visible', false);
    },
    openUploadSampleDialog () {
      dictApi.listByKey('').then(res => {
        console.log(res.data)
      })
      seqProjectApi.listByType('SCIENTIFIC_RESEARCH').then(res => {
        this.projectList = res.data;
        this.$set(this.uploadSampleDialog, 'visible', true);
        this.$set(this.uploadSampleDialog, 'title', '上传样本');
      })
      
    },
    changeType () {
      this.handleQuery();
    },
    addSearchFormData () {
      this.searchFormData.push({})
    },
    delSearchFormData (index) {
      this.searchFormData.splice(index, 1);
    },
    search () {
      this.handleQuery()
      this.searchDialog = false;
    },
    openSearchDialog () {
      this.searchDialog = true;
    },
    closeSearchDialog () {
      this.searchDialog = false;
    },
    sendKafka (row) {
      seqSampleApi.sendKafka(row.id, row.type).then(res =>{
        this.$message({message: '科研样本已发送至Kafka！', type: 'success'});
        this.handleQuery();
      })
    },
    handleQuery() {
      this.loading = true;
      let searchFormData = this.searchFormData;
      searchFormData.push({
          name: 'sampleType',
          searchType: 'EQUAL',
          searchVal: 'SCIENTIFIC_RESEARCH'
        });
      let params = {
        number: this.queryParams.pageNum,
        size: this.queryParams.pageSize,
        criteriaVos: searchFormData,
      };
      seqSampleApi.page(params).then((res) => {
        let data = res.data;
        let that = this;
        let index = 1
        data.content.forEach((v) => {
          v.dataIndex = index++;
          v.layoutText = v.layout ? (v.layout === 'PAIRED' ? '双端测序' : '单端测序') : '-';
          v.typeText = that.typeMap[v.type];
          v.speciesText = that.speciesMap[v.species];
        });
        this.dataList = data.content;
        
        this.total = data.count;
        this.loading = false;
      }).catch(() => {});
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 0,
        pageSize: 10,
        criteriaVos: [{
          name: 'sampleType',
          searchType: 'EQUAL',
          searchVal: 'SCIENTIFIC_RESEARCH'
        }],
      };
      this.searchFormData = [];
      this.handleQuery();
    },
    
    addOrUpdate() {
      let that = this;
      this.formData.sampleType = 'SCIENTIFIC_RESEARCH';
      this.$refs['seqSampleFormRef'].validate((valid) => {
        if (valid) {
          if (this.formData.id) {
            seqSampleApi.update(this.formData).then((res) => {
              this.$message({message: '科研样本更新成功！', type: 'success'});
              that.closeDialog();
            });
          } else {
            seqSampleApi.add(this.formData).then((res) => {
              this.$message({message: '科研样本添加成功！', type: 'success'});
              that.closeDialog();
            });
          }
        } else {
          this.$message.error('必填字段未填写！');
          return false;
        }
      });
    },
    openDialog(row) {
      this.$set(this.dialog, 'visible', true);
      let that = this;
      followDictApi.listByMainName('SEQ_SAMPLE_STRATEGY').then(res1 => {
        this.dictStrategyList = res1.data;
        followDictApi.listByMainName('SEQ_SAMPLE_SPECIES').then(res2 => {
          this.dictSpeciesList = res2.data;

          seqProjectApi.listByType('SCIENTIFIC_RESEARCH').then(res => {
            this.projectList = res.data;
            if (row) {
              this.$set(this.dialog, 'title', '编辑科研样本信息');
              seqSampleApi.get(row.id).then((res) => {
                let data = res.data;
                that.formData = data;

              });
            } else {
              this.$set(this.dialog, 'title', '新增科研样本信息');
              that.formData = {};
            }
          })

        })
      })

      
    },
    closeDialog() {
      this.$set(this.dialog, 'visible', false);
      this.$set(this.dialog, 'title', '');
      this.$refs['seqSampleFormRef'].resetFields();
      this.handleQuery();
    },
    handleDelete(row) {
      if (row) {
        this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          seqSampleApi.delete(row.id).then((res) => {
            this.$message({message: '科研样本删除成功！', type: 'success'});
            this.handleQuery();
          });
        }).catch(() => {});

      } else {
        this.$message.error('暂不支持批量删除科研样本信息！');
      }
    },
    handleSelectionChange(val) {
      this.ids = [];
      val.forEach(v => {
        this.ids.push(v.id);
      });
    },
    handleSelectionRoleChange(rows) {
      if (rows) {
        let arr = [];
        rows.forEach((v) => {
          arr.push(v.id);
        });
        this.selectRoleIdArr = arr;
      }
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.handleQuery();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.handleQuery();
    },
  },
  created() {
    this.handleQuery();
  }
};
</script>

<style scoped>
.el-pagination {
  margin-top: 10px;
  float: right;
  margin-bottom: 10px;
}
/deep/.demo-table-expand {
  font-size: 0;
}
/deep/.demo-table-expand label {
  width: 8%;
  margin-left: 10px;
  color: #99a9bf;
}
/deep/.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 80%;
}
</style>